package com.jinbao.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinbao.springbootinit.annotation.AuthCheck;
import com.jinbao.springbootinit.common.ResultUtils;
import com.jinbao.springbootinit.exception.ThrowUtils;
import com.jinbao.springbootinit.model.dto.chart.*;
import com.jinbao.springbootinit.xfxh.XfManager;
import com.jinbao.springbootinit.common.BaseResponse;
import com.jinbao.springbootinit.common.DeleteRequest;
import com.jinbao.springbootinit.common.ErrorCode;
import com.jinbao.springbootinit.constant.UserConstant;
import com.jinbao.springbootinit.exception.BusinessException;
import com.jinbao.springbootinit.manager.RedisLimiterManager;
import com.jinbao.springbootinit.model.entity.Chart;
import com.jinbao.springbootinit.model.entity.User;
import com.jinbao.springbootinit.model.vo.BiResponse;
import com.jinbao.springbootinit.service.ChartService;
import com.jinbao.springbootinit.service.UserService;
import com.jinbao.springbootinit.utils.ExcelUtils;
import com.jinbao.springbootinit.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 图表接口
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;


    @Resource
    private XfManager xfManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;//限流器

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;//线程池

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }


    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                     HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
                                                       HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                chartService.getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }


    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 智能分析
     *
     * @param multipartFile
     * @param genChatByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> getChatByAi(@RequestPart("file") MultipartFile multipartFile,
                                                GenChatByAiRequest genChatByAiRequest, HttpServletRequest request) {

        String name = genChatByAiRequest.getName();
        String goal = genChatByAiRequest.getGoal();
        String chartType = genChatByAiRequest.getChartType();
        //校验
        if(StringUtils.isAnyBlank(goal)||StringUtils.isAnyBlank(name)||StringUtils.isAnyBlank(chartType)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"有参数为空，请填写参数！");
        }
        if(name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"名称过长");
        }
        if(multipartFile==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件为空，上传！");
        }


        /**
         * 校验文件大小和后缀
         */
        long size=multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();

        //设定文件大小
        final long ONE_MB=1024*1024L;
        if(size>ONE_MB){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件超出1M");
        }
        if(!FileUtil.getSuffix(originalFilename).equals("xlsx")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误，应为.xlsx");
        }
        //校验AI返回的数据对象
        //先检查是否登录
        User  loginUser=userService.getLoginUser(request);

        //限流
        redisLimiterManager.doRateLimit("getChartByAi"+loginUser.getId());


        //模型id
        long biModelId=1654785040361893889L;

        //用户输入
        StringBuilder userInput=new StringBuilder();
        userInput.append("分析目标：").append("\n").append(goal)
                .append("请使用").append(chartType).append("进行数据可视化").append("\n");

        //获取Excel表格文件压缩后的数据
        String result= ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据：").append("\n").append(result);
        String aiResult= null;
        try {
            //拿到返回结果进行拆分
            aiResult = xfManager.doChat(userInput.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        String [] splits=aiResult.split("#####");
        //对拆分的数据进行校验
        if(splits.length<3){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI生成错误,换个方式试试");
        }

        //前端代码
        String genChart=splits[1].trim();
        //结论
        String genResult=splits[2].trim();
        //检查是否为有效的json
        boolean validJson = JsonUtils.isValidJson(genChart);
        if(!validJson){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI生成错误，换个方式试试");
        }

        //插入数据库
        Chart chart=new Chart();
        chart.setName(name);
        chart.setChartType(chartType);
        chart.setChartData(result);
        chart.setStatus("succeed");
        chart.setGoal(goal);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        boolean saveResult=chartService.save(chart);
        if(!saveResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表保存失败");
        }

        BiResponse biResponse=new BiResponse();
        biResponse.setGetChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);

    }

    /**
     * 智能分析(异步)
     *
     * @param multipartFile
     * @param genChatByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> getChatByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                     GenChatByAiRequest genChatByAiRequest, HttpServletRequest request) {

        String name = genChatByAiRequest.getName();
        String goal = genChatByAiRequest.getGoal();
        String chartType = genChatByAiRequest.getChartType();
        //校验
        if(StringUtils.isAnyBlank(goal)||StringUtils.isAnyBlank(name)||StringUtils.isAnyBlank(chartType)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"有参数为空，请填写参数！");
        }
        if(name.length()>20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"名称过长");
        }
        if(multipartFile==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件为空，上传！");
        }


        /**
         * 校验文件大小和后缀
         */
        long size=multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();

        //设定文件大小
        final long ONE_MB=1024*1024L;
        if(size>ONE_MB){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件超出1M");
        }
        if(!FileUtil.getSuffix(originalFilename).equals("xlsx")){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件格式错误，应为.xlsx");
        }
        //校验AI返回的数据对象
        //先检查是否登录
        User  loginUser=userService.getLoginUser(request);

        //限流
        redisLimiterManager.doRateLimit("getChartByAi"+loginUser.getId());


        //模型id
        long biModelId=1654785040361893889L;

        //用户输入
        StringBuilder userInput=new StringBuilder();
        userInput.append("分析目标：").append("\n").append(goal)
                .append("请使用").append(chartType).append("进行数据可视化").append("\n");

        //获取Excel表格文件压缩后的数据
        String result= ExcelUtils.excelToCsv(multipartFile);
        userInput.append("原始数据：").append("\n").append(result);
        /**
         * 异步，先存入数据
         */
        //插入数据库
        Chart chart=new Chart();
        chart.setName(name);
        chart.setChartType(chartType);
        chart.setGoal(goal);
        chart.setChartData(result);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        boolean saveResult=chartService.save(chart);
        if(!saveResult){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表保存失败");
        }


        /**
         * 执行异步操作
         */

        CompletableFuture.runAsync(()->{
            Chart updateChat=new Chart();
            updateChat.setStatus("running");
            updateChat.setId(chart.getId());
            boolean flag=chartService.updateById(updateChat);
            if(!flag){


                throw new BusinessException(ErrorCode.OPERATION_ERROR,"更新图表失败");
            }

            String aiResult;
            try {
                //拿到返回结果进行拆分
                aiResult = xfManager.doChat(userInput.toString());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            String [] splits=aiResult.split("#####");
            //对拆分的数据进行校验
            if(splits.length<3){
                Chart updateChatPro=new Chart();
                updateChatPro.setStatus("failed");
                updateChatPro.setId(chart.getId());
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI生成错误");
            }

            //前端代码
            String genChart=splits[1].trim();
            //结论
            String genResult=splits[2].trim();
            //检查是否为有效的json
            boolean validJson = JsonUtils.isValidJson(genChart);
            if(!validJson){
                Chart updateChatPro=new Chart();
                updateChatPro.setStatus("failed");
                updateChatPro.setId(chart.getId());
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"AI生成错误，换个方式试试");
            }

            //拿到AI结果后再更新一次
            Chart updateChatByAI=new Chart();
            updateChatByAI.setStatus("succeed");
            updateChatByAI.setGenChart(genChart);
            updateChatByAI.setGenResult(genResult);
            updateChatByAI.setId(chart.getId());
            boolean bl=chartService.updateById(updateChatByAI);
            if(!bl){
                Chart updateChatPro=new Chart();
                updateChatPro.setStatus("failed");
                updateChatPro.setId(chart.getId());
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"更新图表失败");
            }

            System.out.println("--------------------");
        },threadPoolExecutor);







        BiResponse biResponse=new BiResponse();
//        biResponse.setGetChart(genChart);
//        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);

    }
}
